import { ref } from 'vue'
import { adapter, request } from '@/request'
import { priceSheetByGet } from '@/core/api/priceSheet'
import type { ProductEnum } from '@/core/enums/platform'
import type { ApproveStatusEnum } from '@/core/enums/status'
import type { PriceSheet } from '@/core/interfaces/priceSheet'
import type { Pagination, RequestWrapper, WithTotalSize } from '@/core/interfaces/common'
import type { ProxyPack, SellerPack } from '@/core/interfaces/base'
import type { TypeEnum } from '@/core/enums/type'
import type { Industry } from '@/core/interfaces/industry'

export interface PriceSheetQuery extends Partial<SellerPack> {
  id?: number
  productId: ProductEnum
  status: string
  keyword: string
  platformNames?: string
  type: TypeEnum
  industryCode?: Industry['code']
  proxyId?: ProxyPack['proxyId']
  approveStatus: ApproveStatusEnum
}

interface Params extends PriceSheetQuery, Pagination {}

export default function getPriceSheet() {
  const service = adapter<RequestWrapper<WithTotalSize<Record<'priceAsks', PriceSheet[]>>>>(request)
  const loading = ref(false)
  const response = ref<WithTotalSize<Record<'priceAsks', PriceSheet[]>>>({
    totalSize: 0,
    priceAsks: []
  })

  const fetch = (params: Params) => {
    const { url, method } = priceSheetByGet()
    loading.value = true

    return service({
      config: {
        url,
        method,
        params
      },
      callback: (res) => {
        res.data.data.priceAsks = res.data.data.priceAsks.map((item) => {
          // 老存量数据可能存在原价没被记录在数据库的情况
          // 出现这种情况后，将提单价赋给原价
          return {
            ...item,
            originalAssessmentPrice: item.originalAssessmentPrice || item.assessmentPrice
          }
        })

        response.value = res.data.data
      },
      error: (err) => {
        console.log(err)
      },
      done: () => {
        loading.value = false
      }
    })
  }

  return [response, fetch, loading] as const
}

export function getAllPriceSheet() {
  const service = adapter<RequestWrapper<WithTotalSize<Record<'priceAsks', PriceSheet[]>>>>(request)
  const loading = ref(false)

  const fetch = (params: Params) => {
    const { url, method } = priceSheetByGet()
    loading.value = true

    return service({
      config: {
        url,
        method,
        params
      },
      callback: (res) => {
        res.data.data.priceAsks = res.data.data.priceAsks.map((item) => {
          // 老存量数据可能存在原价没被记录在数据库的情况
          // 出现这种情况后，将提单价赋给原价
          return {
            ...item,
            originalAssessmentPrice: item.originalAssessmentPrice || item.assessmentPrice
          }
        })
      },
      error: (err) => {
        console.log(err)
      },
      done: () => {
        loading.value = false
      }
    })
  }

  return [null, fetch, loading] as const
}
